package cn.org.book.shop.common.utils.file;

import cn.org.book.shop.common.exception.BaseException;
import cn.org.book.shop.common.utils.bean.CloudFileBean;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * 七牛云上传下载文件
 * Created with IntelliJ IDEA.
 * User:  wanghongjie
 * Date:  2020/11/21 - 21:27
 * <p>
 * Description:
 */
public class QiNiuCloudFileUtils implements CloudFile {

    @Override
    public CloudFileBean upload(byte[] file, CloudFileBean cloudFile) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(cloudFile.accessKey, cloudFile.secretKey);
        String upToken = auth.uploadToken(cloudFile.bucket);
        try {
            Response response = uploadManager.put(file, cloudFile.fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return new CloudFileBean(putRet.key, cloudFile.domainOfBucket);
        } catch (QiniuException e) {
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public CloudFileBean download(CloudFileBean cloudFile) {
        return null;
    }

    @Override
    public CloudFileBean delete(CloudFileBean cloudFile) {
        return null;
    }
}